package com.hnchances.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnchances.common.utils.MD5Utils;
import com.hnchances.common.vo.ChuangSiException;
import com.hnchances.common.vo.Code;
import com.hnchances.common.vo.ResultVo;
import com.hnchances.entity.Student;
import com.hnchances.entity.User;
import com.hnchances.entity.vo.RegisterUser;
import com.hnchances.mapper.StudentMapper;
import com.hnchances.mapper.UserMapper;
import com.hnchances.service.CodeService;
import com.hnchances.service.UserService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-08-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private CodeService codeService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 用户注册
    @Override
    public ResultVo registered(RegisterUser user) {
        String code = codeService.getCode(user.getPhone());
        if(user.getCode() == null){
            return ResultVo.error().message("请输入验证码");
        }
        if (user.getCode().equals(code)) {
            return ResultVo.error().message("验证码错误");
        }

        // 老师情况
        if (user.getClassId() != null) {
            User teacher = new User();
            // 设置默认账号为手机号 密码为123456
            teacher.setUserName(user.getPhone());
            String password = MD5Utils.md5("123456");
            teacher.setPassWord(password);
            teacher.setTrueName(user.getUserName());
            teacher.setPhone(user.getPhone());
            teacher.setClassID(user.getClassId());
            teacher.setCourseID(user.getCourseId());
            teacher.setCreatDateTime(new Date());
            teacher.setIdentity(1);
            teacher.setStatus(0);
            teacher.setVerify(0);
            userMapper.insert(teacher);
            return ResultVo.ok();
        }
        // 学生情况
        String idCard = user.getIdCard();
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("idcard", idCard);
        Student students = studentMapper.selectOne(wrapper);
        Integer classID = students.getClassID();
        Integer studentsId = Math.toIntExact(students.getId());

        if (students != null) {
            User student = new User();
            // 设置默认账号为手机号 密码为123456
            student.setUserName(user.getPhone());
            String password = MD5Utils.md5("123456");
            student.setPassWord(password);
            student.setPhone(user.getPhone());
            student.setTrueName(user.getUserName());
            student.setIdentity(0);
            student.setClassID(classID);
            student.setStudentID(studentsId);
            student.setCreatDateTime(new Date());
            student.setUpdateDateTime(new Date());
            student.setLastLoginDateTime(new Date());
            student.setStatus(0);
            student.setVerify(0);
            userMapper.insert(student);
            return ResultVo.ok();
        }
        return ResultVo.error();
    }


    // 用户登录
    @Override
    public ResultVo login(String userName, String password) {
        if (userName == null || password == null) {
            throw new ChuangSiException(Code.LOGIN_ERROR, "账号或密码为空");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userName", userName);
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            throw new ChuangSiException(Code.LOGIN_ERROR, "账号不存在");
        }
        // 对输入密码进行加密
        String md5Pwd = MD5Utils.md5(password);
        if (!md5Pwd.equals(user.getPassWord())) {
            throw new ChuangSiException(Code.LOGIN_ERROR, "密码错误");
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        JwtBuilder builder = Jwts.builder();
        String token = builder.setSubject(userName) // 主题就是token中携带的数据
                .setIssuedAt(new Date()) //设置token生成时间
                .setId(user.getId().toString()) // 设置用户id位token id
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) //设置过期时间
                .signWith(SignatureAlgorithm.HS256, "zhangxueyang")  //设置加密方式和密码
                .compact();
        return ResultVo.ok().message("登陆成功").data("users", user).data("token", token);

    }

    // 查询用户信息
    @Override
    public ResultVo select(Integer userId) {
        User user = userMapper.selectByUserId(userId);
        return ResultVo.ok().data("user", user);
    }

    @Override
    public ResultVo delete(Integer userId) {
        int i = userMapper.deleteById(userId);
        if (i > 0) {
            return ResultVo.ok();
        } else {
            return ResultVo.error();
        }
    }

    @Override
    public ResultVo updateUser(User user) {
        String passWord = user.getPassWord();
        user.setPassWord(MD5Utils.md5(passWord));
        int i = userMapper.updateById(user);
        if (i > 0) {
            return ResultVo.ok();
        } else {
            return ResultVo.error();
        }
    }

}
